/*
Author : Nguyen Van Ty
Email  : ngvanty03@gmail.com
Date   : 12/23/2010 

*/

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Utility;
using BusinessObject;
using System.Xml;

namespace DataAccessLayer
{
    /// <summary>
    /// Define PhieuNhapHangDao class. This class inherit from  PhieuNhapHangDaoBase class.
    /// If you want add new function, you must define here.
    /// </summary>
    public class PhieuNhapHangDao : PhieuNhapHangDaoBase
    {
        private static ILog logger = null;
        #region Constructor
        /// <summary>
        /// Define Constructor.
        /// </summary>
        public PhieuNhapHangDao() { }
        static PhieuNhapHangDao()
        {
            // Init logger.
            logger = LoggingUtility.GetLogger(typeof(PhieuNhapHangDao).FullName);
        }
        public static Int64 Insert(PhieuNhapHang obj, List<ChiTietPhieuNhapHang> lstChiTietPhieuNhap, NhaCungCap objNhaCungCap)
        {

            String methodName = "InsertPhieuNhapHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            ManagerDao.BeginTransaction();
            //Insert Nha Cung Cap
            int maNCC = int.MinValue;
            if (objNhaCungCap.TenNCC != string.Empty)
            {
                maNCC = NhaCungCapDao.Insert(objNhaCungCap);
                if (maNCC == 0)
                {
                    ManagerDao.Rollback();
                    return 0;
                }
            }
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spInsertPhieuNhapHang");
            //Add value "NguoiNhap"  paramater.
            ManagerDao.AddInParameter(cmd, "NguoiNhap", DbType.String, obj.NguoiNhap);
            //Add value "MaKho"  paramater.
            ManagerDao.AddInParameter(cmd, "MaKho", DbType.Int32, obj.MaKho);
            ManagerDao.AddInParameter(cmd, "MaNCC", DbType.Int32, ConvertValueObject.CastObjValueToInsertDB(maNCC));
            //Add value "NgayNhap"  paramater.
            ManagerDao.AddInParameter(cmd, "NgayNhap", DbType.DateTime, obj.NgayNhap);
            //
            ManagerDao.AddInParameter(cmd, "SysCreatedBy", DbType.String, obj.SysCreatedBy);
            ManagerDao.AddInParameter(cmd, "SysCreatedDate", DbType.DateTime, obj.SysCreatedDate);
            ManagerDao.AddInParameter(cmd, "SysUpdatedBy", DbType.String, obj.SysUpdatedBy);
            ManagerDao.AddInParameter(cmd, "SysUpdatedDate", DbType.DateTime, obj.SysUpdatedDate);
            ManagerDao.AddInParameter(cmd, "IsCommit", DbType.Boolean, obj.IsCommit);
            ManagerDao.AddInParameter(cmd, "GhiChu", DbType.String, obj.GhiChu);
            //add paramater store return value.        
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int64, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {
                ManagerDao.ExecuteNonQuery(cmd);
                Int64 id = Int64.Parse(ManagerDao.GetParameterValue(cmd, "returnValue").ToString());
                if (id > 0)//Successfull.
                {
                    if (lstChiTietPhieuNhap != null && lstChiTietPhieuNhap.Count > 0)
                    {
                        foreach (ChiTietPhieuNhapHang objDetail in lstChiTietPhieuNhap)
                        {
                            objDetail.MaPhieuNhapHang = id;
                            if (!ChiTietPhieuNhapHangDao.Insert(objDetail))
                            {
                                ManagerDao.Rollback();
                                return 0;
                            }
                            if (obj.IsCommit)
                            {
                                MatHangTonKho objMatHangTonKho = new MatHangTonKho();
                                objMatHangTonKho.MaDonViTinh = objDetail.MaDonViTinh;
                                objMatHangTonKho.MaKho = obj.MaKho;
                                objMatHangTonKho.MaMatHang = objDetail.MaMatHang;
                                objMatHangTonKho.SoLuongTon = objDetail.SoLuongNhap;
                                //cong don so luong vo kho
                                if (!MatHangTonKhoDao.Insert(objMatHangTonKho))
                                {
                                    ManagerDao.Rollback();
                                    return 0;
                                }
                            }
                        }
                        ManagerDao.Commit();
                        return id;
                    }
                    else
                    {
                        ManagerDao.Rollback();
                        return 0;
                    }
                }
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
            }
            ManagerDao.Rollback();
            return 0;
        }
        public static List<PhieuNhapHangResult> SearchPhieuNhapHangSomeCondition(PhieuNhapHang t)
        {
            String methodName = "SearchPhieuNhapHangSomeCondition";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {
                List<PhieuNhapHangResult> listPhieuNhapHang = new List<PhieuNhapHangResult>();
                DbCommand cmd = ManagerDao.GetStoredProcCommand("spSearchPhieuNhapHangByCondition");
                //Add value Condition  paramater.
                ManagerDao.AddInParameter(cmd, "Condition", DbType.String, ConvertValueObject.CastObjValueToInsertDB(t.Condition));

                //Add value PageIndex  paramater.
                ManagerDao.AddInParameter(cmd, "PageIndex", DbType.Int32, t.ObjectPaging.PageIndex);
                //Add value PageSize  paramater.
                ManagerDao.AddInParameter(cmd, "PageSize", DbType.Int32, t.ObjectPaging.PageSize);
                //Add value SortField  paramater.
                ManagerDao.AddInParameter(cmd, "SortField", DbType.String, t.ObjectSortOrder.SortField);
                //Add value SortExpression  paramater.
                ManagerDao.AddInParameter(cmd, "SortExpression", DbType.String, t.ObjectSortOrder.SortExpression);
                using (IDataReader reader = ManagerDao.ExecuteReader(cmd))
                {
                    while (reader.Read())
                    {
                        listPhieuNhapHang.Add(GetPhieuNhapHangResultByDataReader(reader));
                        if (t.ToltalRow <= 0)
                            t.ToltalRow = ManagerDao.Getint32DataFromDataReader(reader, "TotalRow");
                    }

                    reader.Close();
                }

                return listPhieuNhapHang;
            }
            catch (Exception ex)
            {
                //write error message to log file.
                logger.Error(methodName, ex);
                return null;
            }
        }
        private static void ValidateDataForUpdate(int khoNew, Int64 maPhieuNhapNew, ref List<ChiTietPhieuNhapHang> lstNew, int khoOld,ref List<ChiTietPhieuNhapHangResult> lstOld)
        {
            if (khoNew != khoOld)
                return;
            int i = 0;
            int j = 0;
            for (i = 0; i < lstNew.Count; i++)
            {
                for (j = 0; j < lstOld.Count; j++)
                {
                    if (maPhieuNhapNew == lstOld[j].MaPhieuNhapHang && lstNew[i].MaMatHang == lstOld[j].MaMatHang)
                    {
                        if (lstNew[i].MaDonViTinh == lstOld[j].MaDonViTinh && lstNew[i].SoLuongNhap == lstOld[j].SoLuongNhap)
                        {
                            lstNew[i].IsAllowUpdate = false;
                            lstOld[j].IsAllowUpdate = false;
                        }
                        break;
                    }
                }
            }
        }
        public static bool Update(PhieuNhapHang obj, List<ChiTietPhieuNhapHang> lstChiTietPhieuNhap, NhaCungCap objNCC)
        {
            //if (obj.IsCommit)
            //    return false;//not update data Is Comitted
            String methodName = "UpdatePhieuNhapHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            ManagerDao.BeginTransaction();

            //get MaKho Cu

            PhieuNhapHang objOldPhieuNhap = Get(obj.MaPhieuNhapHang);
            if (objOldPhieuNhap == null)
            {
                ManagerDao.Rollback();
                return false;

            }
            //Update NhaCungCap

            int maNhaCC = int.MinValue;
            if (objNCC.TenNCC != string.Empty)
            {
                if (objOldPhieuNhap.MaNhaCC <= 0)//insert new nha CC
                {
                    maNhaCC = NhaCungCapDao.Insert(objNCC);
                    if (maNhaCC == 0)
                    {
                        ManagerDao.Rollback();
                        return false;
                    }
                }
                else
                { //Update NCC
                    maNhaCC = objOldPhieuNhap.MaNhaCC;
                    objNCC.MaNCC = maNhaCC;
                    if (!NhaCungCapDao.Update(objNCC))
                    {
                        ManagerDao.Rollback();
                        return false;
                    }
                }
            }
            else
            {
                if (objOldPhieuNhap.MaNhaCC > 0)
                {
                    //Delete Old NNhaCC
                    if (!NhaCungCapDao.Delete(objOldPhieuNhap.MaNhaCC))
                    {
                        ManagerDao.Rollback();
                        return false;
                    }
                }
            }
            
            //ValidateDataForUpdate(obj.MaKho, obj.MaPhieuNhapHang, ref lstChiTietPhieuNhap, objOldPhieuNhap.MaKho, ref lstOldData);
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spUpdatePhieuNhapHang");
            //Add value "MaPhieuNhapHang"  paramater.
            ManagerDao.AddInParameter(cmd, "MaPhieuNhapHang", DbType.Int64, obj.MaPhieuNhapHang);
            //Add value "NguoiNhap"  paramater.
            ManagerDao.AddInParameter(cmd, "NguoiNhap", DbType.String, obj.NguoiNhap);
            //Add value "MaKho"  paramater.
            ManagerDao.AddInParameter(cmd, "MaKho", DbType.Int32, obj.MaKho);
            ManagerDao.AddInParameter(cmd, "MaNCC", DbType.Int32, ConvertValueObject.CastObjValueToInsertDB(maNhaCC));
            //Add value "NgayNhap"  paramater.
            ManagerDao.AddInParameter(cmd, "NgayNhap", DbType.DateTime, obj.NgayNhap);
            ManagerDao.AddInParameter(cmd, "SysUpdatedBy", DbType.String, obj.SysUpdatedBy);
            ManagerDao.AddInParameter(cmd, "SysUpdatedDate", DbType.DateTime, obj.SysUpdatedDate);
            ManagerDao.AddInParameter(cmd, "GhiChu", DbType.String, obj.GhiChu);
            //add paramater store return value.        
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {

                ManagerDao.ExecuteNonQuery(cmd);
                Int32 id = Int32.Parse(ManagerDao.GetParameterValue(cmd, "returnValue").ToString());
                if (id > 0)//Successfull.
                {                    
                    //delete old ChiTietPhieuNhap hang
                    if (!ChiTietPhieuNhapHangDao.DeleteByMaPhieuNhap(obj.MaPhieuNhapHang))
                    {
                        ManagerDao.Rollback();
                        return false;
                    }


                    if (lstChiTietPhieuNhap != null && lstChiTietPhieuNhap.Count > 0)
                    {
                        foreach (ChiTietPhieuNhapHang objDetail in lstChiTietPhieuNhap)
                        {
                            //if (objDetail.IsAllowUpdate)
                            //{
                                objDetail.MaPhieuNhapHang = obj.MaPhieuNhapHang;
                                if (!ChiTietPhieuNhapHangDao.Insert(objDetail))
                                {
                                    ManagerDao.Rollback();
                                    return false;
                                }                

                        }
                    }
                    ManagerDao.Commit();
                    return true;
                }
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
            }
            ManagerDao.Rollback();
            return false;
        }
        public static Boolean CommitPhieuNhapHang(Int64 maPhieuNhapHang, string updatedBy,DateTime updateDate)
        {
            PhieuNhapHang objOldPhieuNhap = Get(maPhieuNhapHang);
            if (objOldPhieuNhap == null)
                return false;
            if (objOldPhieuNhap.IsCommit)
                return false;
            String methodName = "CommitPhieuNhapHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            ManagerDao.BeginTransaction();                     
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spCommitPhieuNhapHang");
            //Add value "MaPhieuNhapHang"  paramater.
            ManagerDao.AddInParameter(cmd, "MaPhieuNhapHang", DbType.Int64, objOldPhieuNhap.MaPhieuNhapHang);
            ManagerDao.AddInParameter(cmd, "SysUpdatedBy", DbType.String, updatedBy);
            ManagerDao.AddInParameter(cmd, "SysUpdatedDate", DbType.DateTime, updateDate);
            //add paramater store return value.        
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {

                ManagerDao.ExecuteNonQuery(cmd);
                Int32 id = Int32.Parse(ManagerDao.GetParameterValue(cmd, "returnValue").ToString());
                if (id > 0)//Successfull.
                {
                    List<ChiTietPhieuNhapHangResult> lstOldData = ChiTietPhieuNhapHangDao.GetByMaPhieuNhapHang(objOldPhieuNhap.MaPhieuNhapHang);
                    if (lstOldData != null && lstOldData.Count > 0)
                    {
                        foreach (ChiTietPhieuNhapHangResult objDetail in lstOldData)
                        {
                            MatHangTonKho objMatHangTonKho = new MatHangTonKho();
                            objMatHangTonKho.MaDonViTinh = objDetail.MaDonViTinh;
                            objMatHangTonKho.MaKho = objOldPhieuNhap.MaKho;
                            objMatHangTonKho.MaMatHang = objDetail.MaMatHang;
                            objMatHangTonKho.SoLuongTon = objDetail.SoLuongNhap;
                            //cong don so luong vo kho
                            if (!MatHangTonKhoDao.Insert(objMatHangTonKho))
                            {
                                ManagerDao.Rollback();
                                return false;
                            }

                        }
                    }
                    ManagerDao.Commit();
                    return true;
                }
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
            }
            ManagerDao.Rollback();
            return false;           
 
        }
        public static Curency GetCurencyForPhieuNhapHang(Int64 maPhieuNhapHang)
        {
            Curency objResult = null;
            String methodName = "GetCurencyForPhieuNhapHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {

                DbCommand dbCommnand = ManagerDao.GetStoredProcCommand("spGetCurencyForPhieuNhapHang");
                //Add value "MaPhieuBanHang"  paramater.
                ManagerDao.AddInParameter(dbCommnand, "MaPhieuNhapHang", DbType.Int64, maPhieuNhapHang);
                IDataReader reader = ManagerDao.ExecuteReader(dbCommnand);
                if (reader.Read())
                {
                    objResult = CurencyDao.GetCurencyByDataReader(reader);
                }
                reader.Close();
            }
            catch (System.Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
            }
            return objResult;
        }

    }
}
        #endregion